// pages/writeform/index.js
var app =getApp();
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
    videoSrc:'',
		canIUse: wx.canIUse('button.open-type.getUserInfo'),
		modalName:null,
		title:'', /// 标题
		imgList: [], // 图片列表
		textareaBValue:'',  //内容

		picker:[

			{
				id: 1,
				text: '楼盘动态'
			},
			{
				id: 2,
				text: '新闻资讯'
			},
			{
				id: 3,
				text: '我的原创'
			},
			{
				id: 4,
				text: '我的日记'
			},
			{
				id: 5,
				text: '热点事件'
			},
			{
				id: 6,
				text: '小道消息'
			},

		],
		selecttype:'楼盘动态',
		selectid:1, // 选择的type
		imgarr:'',
	},
	pickerChange(e){

		var i = e.detail.value;

		this.setData({
			selecttype:this.data.picker[i].text,
			selectid: this.data.picker[i].id,
		})
		console.log(this.data.selecttype)
	}, // 选择type
	/**
	 * 生命周期函数--监听页面加载
	 */
	bindtitle(e){
		this.setData({
			title: e.detail.value
		})
	},// 获取title

	fabu(){
		var that = this;
		var title= that.data.title; // 标题
		var category = that.data.selectid;// 类型
		var photo_url = that.data.imgList; // 图片
		var content = that.data.textareaBValue;//内容
    var video_url = that.data.videoSrc
		console.log(app.globalData);
		var cityCode = wx.getStorageSync('cityCode');
		var opid = wx.getStorageSync('user_new');
		// console.log(opid)
		var imgarr = wx.getStorageSync('imgarr')
		// var imgarr= that.data.imgList;
		var m='';
		if(imgarr){
			m = imgarr.join(',')
		}
		if(title == ""){
			wx.showToast({
				title: '请输入标题',
				icon: 'none',
				duration: 2000
			})
		}
		else if (content == ""){
			wx.showToast({
				title: '请输入内容',
				icon: 'none',
				duration: 2000
			})
		}
		else{
			wx.showLoading({
				title: '发布中',
			})
			app.core('post', "create_article", {
					open_id: opid,
					title:title,
					category: category,
					album: m,
					content: content,
					site_id: cityCode,
          video_url: video_url
				},(res=>{
					console.log(res);
					if (res.resultCode == 200){
						if (wx.getStorageSync('imgarr')) {
							wx.clearStorageSync('imgarr');
						}
						wx.hideLoading()
						wx.showToast({
							title: '发布成功',
							icon: 'none',
							duration: 2000
						})
						setTimeout(function () {
							wx.navigateBack({
								delta: 1
							})
						},300)
					} else if (res.resultCode == 300){
						wx.showToast({
							title: '已有相同的文章,为避免重复请筛选后发布',
							icon: 'none',
							duration: 1000
						})
						// setTimeout(() => {
						//   that.setData({
						//     title: '',
						//     textareaBValue: '',
						//     imgList: []
						//   })
						// },1000)
						console.log('res')
					} else if (res.resultCode == 700){
						wx.showToast({
							title: '文章涉及敏感词/图片违规，请筛选后发布',
							icon: 'none',
							duration: 1000
						})
					}
					else{
						wx.showToast({
							title: '上传失败',
							icon: 'none',
							duration: 3000
						})
					}
				}),
				(err=>{
					wx.showToast({
						title: '网络错误',
						icon: 'none',
						duration: 1000
					})
					wx.hideLoading()
				}))
		}

	},// 发布写一写

	uploadimg(imglist){

		var that = this;
		var num = 0;
		var photo_url= that.data.imgList;
		var imgarr =[];
		console.log(that.data.imgList);
		console.log(imglist);

		wx.showLoading({
			title: '上传中',
			mask: true
		});
		for (var i = 0; i < imglist.length; i++){
			wx.uploadFile({
				url: 'https://xkcloude.hfhouse.com/routineclient/upload_file',
				filePath: photo_url[i],
				name: 'photo_url',
				success(res) {
					num ++
					if (num == (imglist.length)) {
						wx.hideLoading()
					}

					var x = JSON.parse(res.data);
					if (x.resultCode == 200) {
						var x = JSON.parse(res.data);
						console.log(x, 'xxxx')
						imgarr.push(x.data.album[0]);
						wx.setStorageSync('imgarr', imgarr)
					} else if (x.resultCode == 500) {
						wx.showToast({
							title: '上传图片失败',
							icon: 'none',
							duration: 1000
						})

						let  _photo_url = photo_url.slice()
						_photo_url.splice(i-1, 1)

						that.setData({
							imgList: _photo_url
						})


					}
				}
			})
		}
	},


	onLoad: function (options) {
		console.log(options.title)
		if (options.title != undefined && options.title != '') {
			this.setData({
				title: options.title
			})
		}
		if (options.category != undefined && options.category == 3) {
			this.setData({
				selecttype: '我的原创',
				selectid: options.category,
			})
		}
		let that = this
		var opid = getApp().globalData.openid;
		console.log(opid)
		if (opid == '') {
			wx.showModal({
				title: '提示',
				content: '授权后使用此功能',
				success(res) {
					if (res.confirm) {
						console.log('用户点击确定')
						// setTimeout(function () {
						// 	wx.reLaunch({
						// 		url: '/pages/member/index',
						// 	});
						// }, 500)
						that.showModal()
					} else if (res.cancel) {
						wx.navigateBack()
					}
				}
			})
			// return;
		}
		// console.log(opid);
		// var userInfo = wx.getStorageSync('user_info');
		// console.log(userInfo);
		// wx.clearStorageSync('imgarr');
		// let img=wx.getStorageSync('imgarr');
		// console.log(img)
		// wx.setStorageSync('imgarr', '');
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {
		console.log(1111)
		this.setData({
			imgList: []
		})
	},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {

	},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {

	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {

	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: function () {

	},

	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom: function () {

	},

	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage: function () {

	},
  /**
   * 上传视频
   */
  ChooseVideo(){
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success(res) {
        console.log(res,12)
        console.log(res.tempFilePath)
        // that.setData({ videoSrc: res.tempFilePath})
        var tempfilepath = res.tempFilePath
        var size = res.size
        var duration = res.duration
        if (size > (1024 * 1024 * 20)){
          wx.showToast({
            title: '视频大小不能超过20MB',
            icon: "none",
            duration: 2000,
            mask: true
          })
          return false
        }

        if (duration > 10) {
          wx.showToast({
            title: '视频时长不能超过60s',
            icon: "none",
            duration: 2000,
            mask: true
          })
          return false
        }

        wx.showLoading({ title: '上传中...'})
        wx.uploadFile({
          url: 'https://xkcloude.hfhouse.com/routineclient/upload_video',
          filePath: tempfilepath,
          name: 'file',
          success(res) {
            wx.hideLoading()
            console.log(res,666)
            var x = JSON.parse(res.data);
            if (x.resultCode == 200) {
              var videourl = x.data.album[0]
              that.setData({ videoSrc: videourl })
            }else{
                wx.showToast({
                  title: x.msg,
                })
            }
           
          }
        })
      }
    })
  },
	ChooseImage() {
		wx.chooseImage({
			count: 9, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album','camera'], //从相册选择
			success: (res) => {
				//console.log('选择图片' + res);
				// const tempFilePaths = res.tempFilePaths
				// this.setData({
				//   images: this.data.imgList.concat(tempFilePaths)
				// })

				if (this.data.imgList.length != 0) {
					this.setData({
						imgList: this.data.imgList.concat(res.tempFilePaths)
					})
					//this.uploadimg(this.data.imgList.concat(res.tempFilePaths))
					this.uploadimg(this.data.imgList);
				} else{
					this.setData({
						imgList: res.tempFilePaths
					})
					this.uploadimg(res.tempFilePaths)
				}
			}
		});


	},
	ViewImage(e) {
		wx.previewImage({
			urls: this.data.imgList,
			current: e.currentTarget.dataset.url
		});
	},
	DelImg(e) {
		wx.showModal({
			title: '提醒',
			content: '确定要删除这张照片吗？',
			cancelText: '取消',
			confirmText: '确定',
			success: res => {

				if (res.confirm) {
					this.data.imgList.splice(e.currentTarget.dataset.index, 1);
					this.setData({
						imgList: this.data.imgList
					})

					if (this.data.imgList.length == 0) {
						wx.clearStorageSync('imgarr');
						return;
					}

					//this.uploadimg(this.data.imgList)
				}
				// wx.setStorageSync('imgarr', this.data.imgList )
			}
		})
	},

  /**
   * 确认删除视频吗
   */
  bindDeleteVideo(){
    var video_url = this.data.videoSrc
    console.log(video_url,'video_url')
    wx.showModal({
      title: '提醒',
      content: '确定要删除视频吗？',
      cancelText: '取消',
      confirmText: '确定',
      success: res => {
        if (res.confirm) {
         
          this.setData({
            videoSrc: ''
          })

          app.core('post', "delete_video", {video_url: video_url}, (res => {
              console.log(res,66)
          }))
        }
      
      }
    })
  },

	textareaBInput(e) {
		this.setData({
			textareaBValue: e.detail.value
		})
	},


	selectFile() {
		var that = this
		wx.chooseMessageFile({
			count: 1,     //能选择文件的数量
			type: 'file',   //能选择文件的类型,我这里只允许上传文件.还有视频,图片,或者都可以
			success(res) {
				var size = res.tempFiles[0].size;
				var filename = res.tempFiles[0].name;
				var newfilename = filename + "";
				if (size > (1024 * 1024 * 10) || newfilename.indexOf(".mp3")==-1){ //我还限制了文件的大小和具体文件类型
					wx.showToast({
						title: '文件大小不能超过10MB,格式必须为mp3！',
						icon: "none",
						duration: 2000,
						mask: true
					})
				}else{
					that.setData({
						path: res.tempFiles[0].path, //将文件的路径保存在页面的变量上,方便 wx.uploadFile调用
						filename: filename              //渲染到wxml方便用户知道自己选择了什么文件
					})
				}
			}
		})
	},

	showModal(e) {
		this.setData({
			modalName: 'DialogModal1'
		})
	},
	hideModal(e) {
		this.setData({
			modalName: null
		})
		wx.navigateBack()
	},
	getUserInfo: function (e) {
		console.log(e)
		var vm = this;
		var UserInfo = e.detail.userInfo
		// wx.setStorageSync('userInfo', e.detail.userInfo)
		wx.login({
			success(res) {
				console.log(res)
				if (res.code) {
					var userCode = res.code;
					var referrer = wx.getStorageSync('referrer')
					app.core('post', 'create_xcx_user', {
							'nickname': UserInfo.nickName,
							'headpic': UserInfo.avatarUrl,
							'js_code': userCode,
							'referrer': referrer
						}, (res) => {
							console.log(res)
							// return false
							console.log("open_id" + res.data.open_id);
							wx.setStorageSync('userInfo', e.detail.userInfo);
							console.log(wx.getStorageSync('userInfo'));
							wx.setStorageSync('user_new', res.data.open_id);
							wx.setStorageSync('sessionKey', res.sessionKey);
							console.log(wx.getStorageSync('user_new'))

							getApp().globalData.openid = res.data.open_id

							vm.setData({
								userInfo: e.detail.userInfo,
								hasUserInfo: true,
								isMain: true,
								isPower: wx.getStorageSync('user_new')
							});
							wx.hideLoading()
							wx.showToast({
								title: '登录成功',
								icon: 'none'
							})
							vm.setData({
								modalName: null
							})
						},
						(err) => {
							console.log(err)
						}
					)

				} else {
					console.log('登录失败！' + res.errMsg)
				}
			}
		});


	},
})
